<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8" />
    <title>HarmonyOS 综合功能测试</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
    
    <!-- HarmonyOS 优化配置 -->
    <meta name="theme-color" content="#00d4aa" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="default" />
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #00d4aa 0%, #00a693 50%, #007a6b 100%);
            min-height: 100vh;
            color: #333;
        }
        
        .app-container {
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .header {
            background: rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(15px);
            color: white;
            padding: 16px;
            text-align: center;
            font-size: 20px;
            font-weight: 600;
            box-shadow: 0 2px 20px rgba(0,0,0,0.1);
            position: relative;
        }
        
        .back-button {
            position: absolute;
            left: 16px;
            top: 50%;
            transform: translateY(-50%);
            background: rgba(255, 255, 255, 0.2);
            border: none;
            color: white;
            padding: 8px 12px;
            border-radius: 8px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .back-button:hover {
            background: rgba(255, 255, 255, 0.3);
        }
        
        .content {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
        }
        
        .test-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .test-card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 16px;
            padding: 24px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            transition: all 0.3s ease;
        }
        
        .test-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 12px 40px rgba(0,0,0,0.15);
        }
        
        .card-header {
            display: flex;
            align-items: center;
            margin-bottom: 16px;
        }
        
        .card-icon {
            width: 40px;
            height: 40px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 12px;
            font-size: 20px;
        }
        
        .card-title {
            font-size: 18px;
            font-weight: 600;
            color: #2c3e50;
        }
        
        .card-description {
            color: #7f8c8d;
            font-size: 14px;
            margin-bottom: 20px;
            line-height: 1.5;
        }
        
        .test-buttons {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        
        .test-button {
            background: linear-gradient(135deg, #00d4aa, #00a693);
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        .test-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 212, 170, 0.3);
        }
        
        .test-button:active {
            transform: translateY(0);
        }
        
        .test-button.secondary {
            background: linear-gradient(135deg, #74b9ff, #0984e3);
        }
        
        .test-button.warning {
            background: linear-gradient(135deg, #fdcb6e, #e17055);
        }
        
        .test-button.danger {
            background: linear-gradient(135deg, #fd79a8, #e84393);
        }
        
        .result-area {
            margin-top: 16px;
            padding: 12px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #00d4aa;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            max-height: 200px;
            overflow-y: auto;
            white-space: pre-wrap;
            word-break: break-all;
        }
        
        .status-indicator {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 8px;
        }
        
        .status-success { background: #00d4aa; }
        .status-error { background: #e74c3c; }
        .status-warning { background: #f39c12; }
        .status-info { background: #3498db; }
        
        .loading {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid #f3f3f3;
            border-top: 2px solid #00d4aa;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 8px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .footer {
            background: rgba(255, 255, 255, 0.1);
            color: white;
            text-align: center;
            padding: 16px;
            font-size: 14px;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .test-grid {
                grid-template-columns: 1fr;
                padding: 0 10px;
            }
            
            .content {
                padding: 15px;
            }
            
            .test-card {
                padding: 20px;
            }
        }
        
        /* 深色模式支持 */
        @media (prefers-color-scheme: dark) {
            .test-card {
                background: rgba(45, 55, 72, 0.95);
                color: #e2e8f0;
            }
            
            .card-title {
                color: #f7fafc;
            }
            
            .card-description {
                color: #a0aec0;
            }
            
            .result-area {
                background: #2d3748;
                color: #e2e8f0;
            }
        }
    </style>
</head>
<body>
    <div class="app-container">
        <div class="header">
            <button class="back-button" onclick="goBack()">← 返回</button>
            <div>HarmonyOS 综合功能测试</div>
        </div>
        
        <div class="content">
            <div class="test-grid">
                <!-- 相机功能测试 -->
                <div class="test-card">
                    <div class="card-header">
                        <div class="card-icon" style="background: linear-gradient(135deg, #667eea, #764ba2);">📷</div>
                        <div class="card-title">相机功能测试</div>
                    </div>
                    <div class="card-description">
                        测试 HarmonyOS 原生相机功能，包括拍照、录像、前后摄像头切换等功能。
                    </div>
                    <div class="test-buttons">
                        <button class="test-button" onclick="testCamera()">初始化相机</button>
                        <button class="test-button secondary" onclick="takePhoto()">拍照测试</button>
                        <button class="test-button warning" onclick="switchCamera()">切换摄像头</button>
                        <button class="test-button danger" onclick="releaseCamera()">释放相机</button>
                    </div>
                    <div class="test-buttons" style="margin-top: 10px;">
                        <button class="test-button" onclick="testZoom()">变焦测试</button>
                        <button class="test-button secondary" onclick="testFlash()">闪光灯测试</button>
                        <button class="test-button warning" onclick="testVideoRecording()">视频录制</button>
                        <button class="test-button" onclick="testFocus()">对焦测试</button>
                    </div>
                    <div id="camera-result" class="result-area" style="display: none;"></div>
                </div>
                
                <!-- 设备信息测试 -->
                <div class="test-card">
                    <div class="card-header">
                        <div class="card-icon" style="background: linear-gradient(135deg, #ffecd2, #fcb69f);">📱</div>
                        <div class="card-title">设备信息测试</div>
                    </div>
                    <div class="card-description">
                        获取设备基本信息，包括设备型号、系统版本、屏幕信息等。
                    </div>
                    <div class="test-buttons">
                        <button class="test-button" onclick="getDeviceInfo()">获取设备信息</button>
                        <button class="test-button secondary" onclick="getSystemInfo()">获取系统信息</button>
                        <button class="test-button warning" onclick="getScreenInfo()">获取屏幕信息</button>
                    </div>
                    <div id="device-result" class="result-area" style="display: none;"></div>
                </div>
                
                <!-- 存储功能测试 -->
                <div class="test-card">
                    <div class="card-header">
                        <div class="card-icon" style="background: linear-gradient(135deg, #a8edea, #fed6e3);">💾</div>
                        <div class="card-title">存储功能测试</div>
                    </div>
                    <div class="card-description">
                        测试本地存储功能，包括文件读写、数据持久化等。
                    </div>
                    <div class="test-buttons">
                        <button class="test-button" onclick="testStorage()">存储测试数据</button>
                        <button class="test-button secondary" onclick="readStorage()">读取存储数据</button>
                        <button class="test-button warning" onclick="clearStorage()">清空存储</button>
                    </div>
                    <div id="storage-result" class="result-area" style="display: none;"></div>
                </div>
                
                <!-- 网络功能测试 -->
                <div class="test-card">
                    <div class="card-header">
                        <div class="card-icon" style="background: linear-gradient(135deg, #ff9a9e, #fecfef);">🌐</div>
                        <div class="card-title">网络功能测试</div>
                    </div>
                    <div class="card-description">
                        测试网络连接状态、HTTP 请求等网络相关功能。
                    </div>
                    <div class="test-buttons">
                        <button class="test-button" onclick="checkNetwork()">检查网络状态</button>
                        <button class="test-button secondary" onclick="testHttpRequest()">HTTP 请求测试</button>
                        <button class="test-button warning" onclick="testWebSocket()">WebSocket 测试</button>
                    </div>
                    <div id="network-result" class="result-area" style="display: none;"></div>
                </div>
                
                <!-- 传感器测试 -->
                <div class="test-card">
                    <div class="card-header">
                        <div class="card-icon" style="background: linear-gradient(135deg, #fad0c4, #ffd1ff);">🎯</div>
                        <div class="card-title">传感器测试</div>
                    </div>
                    <div class="card-description">
                        测试设备传感器功能，包括加速度计、陀螺仪、指南针等。
                    </div>
                    <div class="test-buttons">
                        <button class="test-button" onclick="testAccelerometer()">加速度计测试</button>
                        <button class="test-button secondary" onclick="testGyroscope()">陀螺仪测试</button>
                        <button class="test-button warning" onclick="testCompass()">指南针测试</button>
                    </div>
                    <div id="sensor-result" class="result-area" style="display: none;"></div>
                </div>
                
                <!-- 权限测试 -->
                <div class="test-card">
                    <div class="card-header">
                        <div class="card-icon" style="background: linear-gradient(135deg, #ff6b6b, #feca57);">🔐</div>
                        <div class="card-title">权限测试</div>
                    </div>
                    <div class="card-description">
                        测试应用权限申请和管理，包括相机、存储、位置等权限。
                    </div>
                    <div class="test-buttons">
                        <button class="test-button" onclick="checkPermissions()">检查权限状态</button>
                        <button class="test-button secondary" onclick="requestPermissions()">申请权限</button>
                        <button class="test-button warning" onclick="openSettings()">打开设置</button>
                    </div>
                    <div id="permission-result" class="result-area" style="display: none;"></div>
                </div>
            </div>
        </div>
        
        <div class="footer">
            HarmonyOS 综合功能测试 v1.0 | 图书管理应用测试套件
        </div>
    </div>

    <script>
        // 全局变量
        let testResults = {};
        
        // 工具函数
        function log(message, type = 'info', targetId = null) {
            const timestamp = new Date().toLocaleTimeString();
            const statusIcon = {
                'success': '✅',
                'error': '❌',
                'warning': '⚠️',
                'info': 'ℹ️'
            }[type] || 'ℹ️';
            
            const logMessage = `[${timestamp}] ${statusIcon} ${message}\n`;
            
            if (targetId) {
                const resultArea = document.getElementById(targetId);
                if (resultArea) {
                    resultArea.style.display = 'block';
                    resultArea.textContent += logMessage;
                    resultArea.scrollTop = resultArea.scrollHeight;
                }
            }
            
            console.log(logMessage);
        }
        
        function clearLog(targetId) {
            const resultArea = document.getElementById(targetId);
            if (resultArea) {
                resultArea.textContent = '';
                resultArea.style.display = 'none';
            }
        }
        
        function showLoading(buttonElement) {
            const originalText = buttonElement.textContent;
            buttonElement.innerHTML = '<span class="loading"></span>处理中...';
            buttonElement.disabled = true;
            
            return () => {
                buttonElement.textContent = originalText;
                buttonElement.disabled = false;
            };
        }
        
        // 相机功能测试
        let cameraInstance = null;
        let currentCameraIndex = 0; // 0: 后置, 1: 前置
        
        async function testCamera() {
            const hideLoading = showLoading(event.target);
            clearLog('camera-result');
            
            try {
                log('开始初始化相机...', 'info', 'camera-result');
                
                // 检查是否有 CameraBridge 接口
                if (window.CameraBridge) {
                    log('发现 CameraBridge 相机接口', 'success', 'camera-result');
                    
                    try {
                        // 创建相机实例
                        cameraInstance = new window.CameraBridge();
                        
                        // 生成预览 Surface ID
                        const surfaceId = `preview_surface_${Date.now()}`;
                        
                        // 初始化相机
                        await cameraInstance.initializeCamera(surfaceId, {
                            cameraDeviceIndex: currentCameraIndex,
                            focusMode: 1, // 自动对焦
                            quality: 95
                        });
                        
                        log('相机初始化成功', 'success', 'camera-result');
                        log(`Surface ID: ${surfaceId}`, 'info', 'camera-result');
                        log(`相机设备索引: ${currentCameraIndex} (${currentCameraIndex === 0 ? '后置' : '前置'})`, 'info', 'camera-result');
                        
                        // 检查相机状态
                        const isReady = cameraInstance.isReady();
                        log(`相机就绪状态: ${isReady}`, isReady ? 'success' : 'error', 'camera-result');
                        
                    } catch (initError) {
                        log(`相机初始化失败: ${initError.message}`, 'error', 'camera-result');
                        cameraInstance = null;
                    }
                    
                } else if (window.HarmonyBridge && window.HarmonyBridge.camera) {
                    log('发现 HarmonyBridge 相机接口 (旧版)', 'warning', 'camera-result');
                    
                    const isAvailable = await window.HarmonyBridge.camera.isAvailable();
                    log(`相机可用性: ${isAvailable}`, isAvailable ? 'success' : 'error', 'camera-result');
                    
                    if (isAvailable) {
                        const initResult = await window.HarmonyBridge.camera.initialize();
                        log(`相机初始化结果: ${JSON.stringify(initResult)}`, initResult ? 'success' : 'error', 'camera-result');
                    }
                } else {
                    log('未找到 CameraBridge 相机接口', 'warning', 'camera-result');
                    log('尝试使用 Web API...', 'info', 'camera-result');
                    
                    // 尝试使用 Web API
                    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                        const stream = await navigator.mediaDevices.getUserMedia({ video: true });
                        log('Web API 相机访问成功', 'success', 'camera-result');
                        stream.getTracks().forEach(track => track.stop());
                    } else {
                        log('Web API 相机不可用', 'error', 'camera-result');
                    }
                }
            } catch (error) {
                log(`相机测试失败: ${error.message}`, 'error', 'camera-result');
            } finally {
                hideLoading();
            }
        }
        
        async function takePhoto() {
            const hideLoading = showLoading(event.target);
            
            try {
                log('开始拍照测试...', 'info', 'camera-result');
                
                if (cameraInstance && cameraInstance.isReady()) {
                    log('使用 CameraBridge 拍照', 'info', 'camera-result');
                    
                    try {
                        // 使用带设置的拍照方法
                        const photoPath = await cameraInstance.takePhoto({
                            quality: 95,
                            allowEdit: false,
                            resultType: 'file',
                            cameraDeviceIndex: currentCameraIndex
                        });
                        
                        log(`拍照成功! 照片路径: ${photoPath}`, 'success', 'camera-result');
                        log(`照片保存位置: ${photoPath}`, 'info', 'camera-result');
                        
                        // 也可以尝试简单拍照方法
                        log('尝试简单拍照方法...', 'info', 'camera-result');
                        const simplePhotoPath = await cameraInstance.takePictureSimple();
                        log(`简单拍照成功! 路径: ${simplePhotoPath}`, 'success', 'camera-result');
                        
                    } catch (photoError) {
                        log(`拍照失败: ${photoError.message}`, 'error', 'camera-result');
                    }
                    
                } else if (window.HarmonyBridge && window.HarmonyBridge.camera) {
                    log('使用 HarmonyBridge 拍照 (旧版)', 'warning', 'camera-result');
                    
                    const result = await window.HarmonyBridge.camera.takePhoto({
                        quality: 0.8,
                        format: 'jpeg'
                    });
                    
                    if (result.success) {
                        log(`拍照成功! 数据长度: ${result.data ? result.data.length : 0}`, 'success', 'camera-result');
                        log(`格式: ${result.format}, 时间戳: ${result.timestamp}`, 'info', 'camera-result');
                    } else {
                        log(`拍照失败: ${result.error}`, 'error', 'camera-result');
                    }
                } else {
                    log('相机未初始化或接口不可用，无法拍照', 'error', 'camera-result');
                    log('请先点击"初始化相机"按钮', 'warning', 'camera-result');
                }
            } catch (error) {
                log(`拍照测试失败: ${error.message}`, 'error', 'camera-result');
            } finally {
                hideLoading();
            }
        }
        
        async function switchCamera() {
            const hideLoading = showLoading(event.target);
            
            try {
                log('切换摄像头...', 'info', 'camera-result');
                
                if (cameraInstance && cameraInstance.isReady()) {
                    log('使用 CameraBridge 切换摄像头', 'info', 'camera-result');
                    
                    try {
                        // 先释放当前相机
                        await cameraInstance.releaseCamera();
                        log('当前相机已释放', 'info', 'camera-result');
                        
                        // 切换摄像头索引
                        currentCameraIndex = currentCameraIndex === 0 ? 1 : 0;
                        log(`切换到${currentCameraIndex === 0 ? '后置' : '前置'}摄像头`, 'info', 'camera-result');
                        
                        // 重新初始化相机
                        const surfaceId = `preview_surface_${Date.now()}`;
                        await cameraInstance.initializeCamera(surfaceId, {
                            cameraDeviceIndex: currentCameraIndex,
                            focusMode: 1,
                            quality: 95
                        });
                        
                        log(`摄像头切换成功! 当前使用: ${currentCameraIndex === 0 ? '后置' : '前置'}摄像头`, 'success', 'camera-result');
                        
                    } catch (switchError) {
                        log(`摄像头切换失败: ${switchError.message}`, 'error', 'camera-result');
                        // 尝试恢复到原来的摄像头
                        currentCameraIndex = currentCameraIndex === 0 ? 1 : 0;
                    }
                    
                } else if (window.HarmonyBridge && window.HarmonyBridge.camera) {
                    log('使用 HarmonyBridge 切换摄像头 (旧版)', 'warning', 'camera-result');
                    
                    const result = await window.HarmonyBridge.camera.switchCamera();
                    log(`摄像头切换结果: ${result}`, result ? 'success' : 'error', 'camera-result');
                } else {
                    log('相机未初始化或接口不可用，无法切换摄像头', 'error', 'camera-result');
                    log('请先点击"初始化相机"按钮', 'warning', 'camera-result');
                }
            } catch (error) {
                log(`摄像头切换失败: ${error.message}`, 'error', 'camera-result');
            } finally {
                hideLoading();
            }
        }
        
        async function releaseCamera() {
            const hideLoading = showLoading(event.target);
            
            try {
                log('释放相机资源...', 'info', 'camera-result');
                
                if (cameraInstance) {
                    log('使用 CameraBridge 释放相机', 'info', 'camera-result');
                    
                    try {
                        // 先释放会话
                        await cameraInstance.releaseSession();
                        log('相机会话已释放', 'info', 'camera-result');
                        
                        // 再释放相机
                        await cameraInstance.releaseCamera();
                        log('相机资源释放成功', 'success', 'camera-result');
                        
                        // 清理实例
                        cameraInstance = null;
                        currentCameraIndex = 0;
                        
                    } catch (releaseError) {
                        log(`相机释放过程中出现错误: ${releaseError.message}`, 'warning', 'camera-result');
                        // 即使出错也清理实例
                        cameraInstance = null;
                        currentCameraIndex = 0;
                    }
                    
                } else if (window.HarmonyBridge && window.HarmonyBridge.camera) {
                    log('使用 HarmonyBridge 释放相机 (旧版)', 'warning', 'camera-result');
                    
                    await window.HarmonyBridge.camera.release();
                    log('相机资源释放成功', 'success', 'camera-result');
                } else {
                    log('没有需要释放的相机资源', 'warning', 'camera-result');
                }
            } catch (error) {
                log(`相机资源释放失败: ${error.message}`, 'error', 'camera-result');
            } finally {
                hideLoading();
            }
        }
        
        // 变焦测试
        async function testZoom() {
            const hideLoading = showLoading(event.target);
            
            try {
                log('开始变焦测试...', 'info', 'camera-result');
                
                if (cameraInstance && cameraInstance.isReady()) {
                    log('测试不同变焦比例', 'info', 'camera-result');
                    
                    const zoomLevels = [1.0, 2.0, 3.0, 1.5, 1.0]; // 测试不同变焦级别
                    
                    for (let i = 0; i < zoomLevels.length; i++) {
                        const zoomRatio = zoomLevels[i];
                        try {
                            await cameraInstance.setZoomRatio(zoomRatio);
                            log(`变焦设置成功: ${zoomRatio}x`, 'success', 'camera-result');
                            
                            // 等待一秒再设置下一个变焦级别
                            if (i < zoomLevels.length - 1) {
                                await new Promise(resolve => setTimeout(resolve, 1000));
                            }
                        } catch (zoomError) {
                            log(`变焦 ${zoomRatio}x 设置失败: ${zoomError.message}`, 'error', 'camera-result');
                        }
                    }
                    
                    log('变焦测试完成', 'success', 'camera-result');
                } else {
                    log('相机未初始化，无法进行变焦测试', 'error', 'camera-result');
                    log('请先点击"初始化相机"按钮', 'warning', 'camera-result');
                }
            } catch (error) {
                log(`变焦测试失败: ${error.message}`, 'error', 'camera-result');
            } finally {
                hideLoading();
            }
        }
        
        // 闪光灯测试
        async function testFlash() {
            const hideLoading = showLoading(event.target);
            
            try {
                log('开始闪光灯测试...', 'info', 'camera-result');
                
                if (cameraInstance && cameraInstance.isReady()) {
                    log('测试不同闪光灯模式', 'info', 'camera-result');
                    
                    const flashModes = [
                        { mode: 0, name: '关闭' },
                        { mode: 1, name: '开启' },
                        { mode: 2, name: '自动' },
                        { mode: 0, name: '关闭' } // 最后关闭
                    ];
                    
                    for (let i = 0; i < flashModes.length; i++) {
                        const { mode, name } = flashModes[i];
                        try {
                            await cameraInstance.setFlashMode(mode);
                            log(`闪光灯模式设置成功: ${name} (${mode})`, 'success', 'camera-result');
                            
                            // 等待一秒再设置下一个模式
                            if (i < flashModes.length - 1) {
                                await new Promise(resolve => setTimeout(resolve, 1000));
                            }
                        } catch (flashError) {
                            log(`闪光灯模式 ${name} 设置失败: ${flashError.message}`, 'error', 'camera-result');
                        }
                    }
                    
                    log('闪光灯测试完成', 'success', 'camera-result');
                } else {
                    log('相机未初始化，无法进行闪光灯测试', 'error', 'camera-result');
                    log('请先点击"初始化相机"按钮', 'warning', 'camera-result');
                }
            } catch (error) {
                log(`闪光灯测试失败: ${error.message}`, 'error', 'camera-result');
            } finally {
                hideLoading();
            }
        }
        
        // 视频录制测试
        let isRecording = false;
        async function testVideoRecording() {
            const hideLoading = showLoading(event.target);
            
            try {
                if (!isRecording) {
                    log('开始视频录制测试...', 'info', 'camera-result');
                    
                    if (cameraInstance && cameraInstance.isReady()) {
                        try {
                            // 生成视频Surface ID
                            const videoSurfaceId = `video_surface_${Date.now()}`;
                            const photoSurfaceId = `photo_surface_${Date.now()}`;
                            
                            // 开始录制
                            await cameraInstance.startVideoRecording(videoSurfaceId, photoSurfaceId);
                            log('视频录制开始', 'success', 'camera-result');
                            log(`视频Surface ID: ${videoSurfaceId}`, 'info', 'camera-result');
                            
                            // 获取视频帧信息
                            try {
                                const frameInfo = await cameraInstance.getVideoFrameInfo();
                                log(`视频帧信息: ${frameInfo.width}x${frameInfo.height} @ ${frameInfo.frameRate}fps`, 'info', 'camera-result');
                            } catch (frameError) {
                                log(`获取视频帧信息失败: ${frameError.message}`, 'warning', 'camera-result');
                            }
                            
                            isRecording = true;
                            event.target.textContent = '停止录制';
                            event.target.classList.add('danger');
                            
                            // 5秒后自动停止录制
                            setTimeout(async () => {
                                if (isRecording) {
                                    await stopVideoRecording();
                                }
                            }, 5000);
                            
                        } catch (recordError) {
                            log(`视频录制开始失败: ${recordError.message}`, 'error', 'camera-result');
                        }
                    } else {
                        log('相机未初始化，无法进行视频录制', 'error', 'camera-result');
                        log('请先点击"初始化相机"按钮', 'warning', 'camera-result');
                    }
                } else {
                    await stopVideoRecording();
                }
            } catch (error) {
                log(`视频录制测试失败: ${error.message}`, 'error', 'camera-result');
            } finally {
                hideLoading();
            }
        }
        
        async function stopVideoRecording() {
            try {
                if (cameraInstance && isRecording) {
                    await cameraInstance.stopVideoRecording();
                    log('视频录制停止', 'success', 'camera-result');
                    
                    isRecording = false;
                    const button = document.querySelector('button[onclick="testVideoRecording()"]');
                    if (button) {
                        button.textContent = '视频录制';
                        button.classList.remove('danger');
                    }
                }
            } catch (error) {
                log(`停止视频录制失败: ${error.message}`, 'error', 'camera-result');
            }
        }
        
        // 对焦测试
        async function testFocus() {
            const hideLoading = showLoading(event.target);
            
            try {
                log('开始对焦测试...', 'info', 'camera-result');
                
                if (cameraInstance && cameraInstance.isReady()) {
                    log('测试不同对焦点', 'info', 'camera-result');
                    
                    const focusPoints = [
                        { x: 0.5, y: 0.5, name: '中心' },
                        { x: 0.2, y: 0.2, name: '左上角' },
                        { x: 0.8, y: 0.2, name: '右上角' },
                        { x: 0.2, y: 0.8, name: '左下角' },
                        { x: 0.8, y: 0.8, name: '右下角' },
                        { x: 0.5, y: 0.5, name: '中心（恢复）' }
                    ];
                    
                    for (let i = 0; i < focusPoints.length; i++) {
                        const { x, y, name } = focusPoints[i];
                        try {
                            await cameraInstance.setFocusPoint(x, y);
                            log(`对焦点设置成功: ${name} (${x}, ${y})`, 'success', 'camera-result');
                            
                            // 等待一秒再设置下一个对焦点
                            if (i < focusPoints.length - 1) {
                                await new Promise(resolve => setTimeout(resolve, 1000));
                            }
                        } catch (focusError) {
                            log(`对焦点 ${name} 设置失败: ${focusError.message}`, 'error', 'camera-result');
                        }
                    }
                    
                    // 测试视频防抖
                    try {
                        log('测试视频防抖功能...', 'info', 'camera-result');
                        await cameraInstance.checkVideoStabilization(1); // 测试防抖模式1
                        log('视频防抖模式1支持', 'success', 'camera-result');
                    } catch (stabilizationError) {
                        log(`视频防抖测试: ${stabilizationError.message}`, 'warning', 'camera-result');
                    }
                    
                    log('对焦测试完成', 'success', 'camera-result');
                } else {
                    log('相机未初始化，无法进行对焦测试', 'error', 'camera-result');
                    log('请先点击"初始化相机"按钮', 'warning', 'camera-result');
                }
            } catch (error) {
                log(`对焦测试失败: ${error.message}`, 'error', 'camera-result');
            } finally {
                hideLoading();
            }
        }
        
        // 设备信息测试
        async function getDeviceInfo() {
            const hideLoading = showLoading(event.target);
            clearLog('device-result');
            
            try {
                log('获取设备信息...', 'info', 'device-result');
                
                // 基本设备信息
                const deviceInfo = {
                    userAgent: navigator.userAgent,
                    platform: navigator.platform,
                    language: navigator.language,
                    cookieEnabled: navigator.cookieEnabled,
                    onLine: navigator.onLine,
                    hardwareConcurrency: navigator.hardwareConcurrency
                };
                
                log(`设备信息:`, 'success', 'device-result');
                log(JSON.stringify(deviceInfo, null, 2), 'info', 'device-result');
                
                // 尝试获取 HarmonyOS 特定信息
                if (window.HarmonyBridge && window.HarmonyBridge.device) {
                    const harmonyInfo = await window.HarmonyBridge.device.getDeviceInfo();
                    log(`HarmonyOS 设备信息:`, 'success', 'device-result');
                    log(JSON.stringify(harmonyInfo, null, 2), 'info', 'device-result');
                }
            } catch (error) {
                log(`获取设备信息失败: ${error.message}`, 'error', 'device-result');
            } finally {
                hideLoading();
            }
        }
        
        async function getSystemInfo() {
            const hideLoading = showLoading(event.target);
            
            try {
                log('获取系统信息...', 'info', 'device-result');
                
                const systemInfo = {
                    timestamp: new Date().toISOString(),
                    timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
                    memory: performance.memory ? {
                        used: Math.round(performance.memory.usedJSHeapSize / 1024 / 1024) + ' MB',
                        total: Math.round(performance.memory.totalJSHeapSize / 1024 / 1024) + ' MB',
                        limit: Math.round(performance.memory.jsHeapSizeLimit / 1024 / 1024) + ' MB'
                    } : '不可用'
                };
                
                log(`系统信息:`, 'success', 'device-result');
                log(JSON.stringify(systemInfo, null, 2), 'info', 'device-result');
            } catch (error) {
                log(`获取系统信息失败: ${error.message}`, 'error', 'device-result');
            } finally {
                hideLoading();
            }
        }
        
        async function getScreenInfo() {
            const hideLoading = showLoading(event.target);
            
            try {
                log('获取屏幕信息...', 'info', 'device-result');
                
                const screenInfo = {
                    width: screen.width,
                    height: screen.height,
                    availWidth: screen.availWidth,
                    availHeight: screen.availHeight,
                    colorDepth: screen.colorDepth,
                    pixelDepth: screen.pixelDepth,
                    devicePixelRatio: window.devicePixelRatio,
                    innerWidth: window.innerWidth,
                    innerHeight: window.innerHeight
                };
                
                log(`屏幕信息:`, 'success', 'device-result');
                log(JSON.stringify(screenInfo, null, 2), 'info', 'device-result');
            } catch (error) {
                log(`获取屏幕信息失败: ${error.message}`, 'error', 'device-result');
            } finally {
                hideLoading();
            }
        }
        
        // 存储功能测试
        async function testStorage() {
            const hideLoading = showLoading(event.target);
            clearLog('storage-result');
            
            try {
                log('测试存储功能...', 'info', 'storage-result');
                
                const testData = {
                    timestamp: new Date().toISOString(),
                    testValue: Math.random(),
                    message: '这是一个测试数据'
                };
                
                // 测试 localStorage
                localStorage.setItem('harmonyos-test', JSON.stringify(testData));
                log('localStorage 写入成功', 'success', 'storage-result');
                
                // 测试 sessionStorage
                sessionStorage.setItem('harmonyos-session-test', JSON.stringify(testData));
                log('sessionStorage 写入成功', 'success', 'storage-result');
                
                // 测试 HarmonyOS 原生存储
                if (window.HarmonyBridge && window.HarmonyBridge.storage) {
                    await window.HarmonyBridge.storage.setItem('native-test', testData);
                    log('HarmonyOS 原生存储写入成功', 'success', 'storage-result');
                }
                
                log(`测试数据: ${JSON.stringify(testData)}`, 'info', 'storage-result');
            } catch (error) {
                log(`存储测试失败: ${error.message}`, 'error', 'storage-result');
            } finally {
                hideLoading();
            }
        }
        
        async function readStorage() {
            const hideLoading = showLoading(event.target);
            
            try {
                log('读取存储数据...', 'info', 'storage-result');
                
                // 读取 localStorage
                const localData = localStorage.getItem('harmonyos-test');
                if (localData) {
                    log(`localStorage 数据: ${localData}`, 'success', 'storage-result');
                } else {
                    log('localStorage 无数据', 'warning', 'storage-result');
                }
                
                // 读取 sessionStorage
                const sessionData = sessionStorage.getItem('harmonyos-session-test');
                if (sessionData) {
                    log(`sessionStorage 数据: ${sessionData}`, 'success', 'storage-result');
                } else {
                    log('sessionStorage 无数据', 'warning', 'storage-result');
                }
                
                // 读取 HarmonyOS 原生存储
                if (window.HarmonyBridge && window.HarmonyBridge.storage) {
                    const nativeData = await window.HarmonyBridge.storage.getItem('native-test');
                    if (nativeData) {
                        log(`HarmonyOS 原生存储数据: ${JSON.stringify(nativeData)}`, 'success', 'storage-result');
                    } else {
                        log('HarmonyOS 原生存储无数据', 'warning', 'storage-result');
                    }
                }
            } catch (error) {
                log(`读取存储失败: ${error.message}`, 'error', 'storage-result');
            } finally {
                hideLoading();
            }
        }
        
        async function clearStorage() {
            const hideLoading = showLoading(event.target);
            
            try {
                log('清空存储数据...', 'info', 'storage-result');
                
                localStorage.removeItem('harmonyos-test');
                sessionStorage.removeItem('harmonyos-session-test');
                log('Web 存储清空成功', 'success', 'storage-result');
                
                if (window.HarmonyBridge && window.HarmonyBridge.storage) {
                    await window.HarmonyBridge.storage.removeItem('native-test');
                    log('HarmonyOS 原生存储清空成功', 'success', 'storage-result');
                }
            } catch (error) {
                log(`清空存储失败: ${error.message}`, 'error', 'storage-result');
            } finally {
                hideLoading();
            }
        }
        
        // 网络功能测试
        async function checkNetwork() {
            const hideLoading = showLoading(event.target);
            clearLog('network-result');
            
            try {
                log('检查网络状态...', 'info', 'network-result');
                
                const networkInfo = {
                    online: navigator.onLine,
                    connection: navigator.connection ? {
                        effectiveType: navigator.connection.effectiveType,
                        downlink: navigator.connection.downlink,
                        rtt: navigator.connection.rtt,
                        saveData: navigator.connection.saveData
                    } : '不可用'
                };
                
                log(`网络状态: ${JSON.stringify(networkInfo, null, 2)}`, 'success', 'network-result');
                
                // 测试网络连通性
                const startTime = performance.now();
                try {
                    await fetch('https://www.baidu.com', { mode: 'no-cors' });
                    const endTime = performance.now();
                    log(`网络连通性测试成功，耗时: ${Math.round(endTime - startTime)}ms`, 'success', 'network-result');
                } catch (fetchError) {
                    log(`网络连通性测试失败: ${fetchError.message}`, 'warning', 'network-result');
                }
            } catch (error) {
                log(`网络检查失败: ${error.message}`, 'error', 'network-result');
            } finally {
                hideLoading();
            }
        }
        
        async function testHttpRequest() {
            const hideLoading = showLoading(event.target);
            
            try {
                log('测试 HTTP 请求...', 'info', 'network-result');
                
                const testUrl = 'https://jsonplaceholder.typicode.com/posts/1';
                const startTime = performance.now();
                
                const response = await fetch(testUrl);
                const data = await response.json();
                const endTime = performance.now();
                
                log(`HTTP 请求成功，耗时: ${Math.round(endTime - startTime)}ms`, 'success', 'network-result');
                log(`响应状态: ${response.status} ${response.statusText}`, 'info', 'network-result');
                log(`响应数据: ${JSON.stringify(data, null, 2)}`, 'info', 'network-result');
            } catch (error) {
                log(`HTTP 请求失败: ${error.message}`, 'error', 'network-result');
            } finally {
                hideLoading();
            }
        }
        
        async function testWebSocket() {
            const hideLoading = showLoading(event.target);
            
            try {
                log('测试 WebSocket 连接...', 'info', 'network-result');
                
                // 使用公共的 WebSocket 测试服务
                const ws = new WebSocket('wss://echo.websocket.org');
                
                ws.onopen = function() {
                    log('WebSocket 连接成功', 'success', 'network-result');
                    ws.send('Hello HarmonyOS!');
                };
                
                ws.onmessage = function(event) {
                    log(`WebSocket 收到消息: ${event.data}`, 'success', 'network-result');
                    ws.close();
                };
                
                ws.onerror = function(error) {
                    log(`WebSocket 错误: ${error}`, 'error', 'network-result');
                };
                
                ws.onclose = function() {
                    log('WebSocket 连接关闭', 'info', 'network-result');
                    hideLoading();
                };
                
                // 10秒超时
                setTimeout(() => {
                    if (ws.readyState === WebSocket.CONNECTING) {
                        ws.close();
                        log('WebSocket 连接超时', 'warning', 'network-result');
                        hideLoading();
                    }
                }, 10000);
            } catch (error) {
                log(`WebSocket 测试失败: ${error.message}`, 'error', 'network-result');
                hideLoading();
            }
        }
        
        // 传感器测试
        async function testAccelerometer() {
            const hideLoading = showLoading(event.target);
            clearLog('sensor-result');
            
            try {
                log('测试加速度计...', 'info', 'sensor-result');
                
                if ('DeviceMotionEvent' in window) {
                    let count = 0;
                    const maxCount = 10;
                    
                    const handleMotion = (event) => {
                        if (count < maxCount) {
                            const acceleration = event.acceleration || event.accelerationIncludingGravity;
                            if (acceleration) {
                                log(`加速度 [${count + 1}]: x=${acceleration.x?.toFixed(2)}, y=${acceleration.y?.toFixed(2)}, z=${acceleration.z?.toFixed(2)}`, 'success', 'sensor-result');
                                count++;
                            }
                        } else {
                            window.removeEventListener('devicemotion', handleMotion);
                            log('加速度计测试完成', 'success', 'sensor-result');
                            hideLoading();
                        }
                    };
                    
                    window.addEventListener('devicemotion', handleMotion);
                    
                    // 5秒后自动停止
                    setTimeout(() => {
                        window.removeEventListener('devicemotion', handleMotion);
                        if (count === 0) {
                            log('加速度计不可用或无权限', 'warning', 'sensor-result');
                        }
                        hideLoading();
                    }, 5000);
                } else {
                    log('设备不支持加速度计', 'warning', 'sensor-result');
                    hideLoading();
                }
            } catch (error) {
                log(`加速度计测试失败: ${error.message}`, 'error', 'sensor-result');
                hideLoading();
            }
        }
        
        async function testGyroscope() {
            const hideLoading = showLoading(event.target);
            
            try {
                log('测试陀螺仪...', 'info', 'sensor-result');
                
                if ('DeviceOrientationEvent' in window) {
                    let count = 0;
                    const maxCount = 10;
                    
                    const handleOrientation = (event) => {
                        if (count < maxCount) {
                            log(`陀螺仪 [${count + 1}]: α=${event.alpha?.toFixed(2)}, β=${event.beta?.toFixed(2)}, γ=${event.gamma?.toFixed(2)}`, 'success', 'sensor-result');
                            count++;
                        } else {
                            window.removeEventListener('deviceorientation', handleOrientation);
                            log('陀螺仪测试完成', 'success', 'sensor-result');
                            hideLoading();
                        }
                    };
                    
                    window.addEventListener('deviceorientation', handleOrientation);
                    
                    // 5秒后自动停止
                    setTimeout(() => {
                        window.removeEventListener('deviceorientation', handleOrientation);
                        if (count === 0) {
                            log('陀螺仪不可用或无权限', 'warning', 'sensor-result');
                        }
                        hideLoading();
                    }, 5000);
                } else {
                    log('设备不支持陀螺仪', 'warning', 'sensor-result');
                    hideLoading();
                }
            } catch (error) {
                log(`陀螺仪测试失败: ${error.message}`, 'error', 'sensor-result');
                hideLoading();
            }
        }
        
        async function testCompass() {
            const hideLoading = showLoading(event.target);
            
            try {
                log('测试指南针...', 'info', 'sensor-result');
                
                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(
                        (position) => {
                            const coords = position.coords;
                            log(`位置信息: 纬度=${coords.latitude}, 经度=${coords.longitude}`, 'success', 'sensor-result');
                            if (coords.heading !== null) {
                                log(`方向: ${coords.heading}°`, 'success', 'sensor-result');
                            } else {
                                log('方向信息不可用', 'warning', 'sensor-result');
                            }
                            hideLoading();
                        },
                        (error) => {
                            log(`位置获取失败: ${error.message}`, 'error', 'sensor-result');
                            hideLoading();
                        },
                        { enableHighAccuracy: true, timeout: 10000 }
                    );
                } else {
                    log('设备不支持地理位置', 'warning', 'sensor-result');
                    hideLoading();
                }
            } catch (error) {
                log(`指南针测试失败: ${error.message}`, 'error', 'sensor-result');
                hideLoading();
            }
        }
        
        // 权限测试
        async function checkPermissions() {
            const hideLoading = showLoading(event.target);
            clearLog('permission-result');
            
            try {
                log('检查权限状态...', 'info', 'permission-result');
                
                const permissions = ['camera', 'microphone', 'geolocation', 'notifications'];
                
                for (const permission of permissions) {
                    try {
                        if (navigator.permissions) {
                            const result = await navigator.permissions.query({ name: permission });
                            log(`${permission}: ${result.state}`, result.state === 'granted' ? 'success' : 'warning', 'permission-result');
                        } else {
                            log(`${permission}: 权限 API 不可用`, 'warning', 'permission-result');
                        }
                    } catch (error) {
                        log(`${permission}: 检查失败 - ${error.message}`, 'error', 'permission-result');
                    }
                }
                
                // 检查 HarmonyOS 特定权限
                if (window.HarmonyBridge && window.HarmonyBridge.permissions) {
                    const harmonyPermissions = await window.HarmonyBridge.permissions.checkAll();
                    log(`HarmonyOS 权限状态: ${JSON.stringify(harmonyPermissions, null, 2)}`, 'info', 'permission-result');
                }
            } catch (error) {
                log(`权限检查失败: ${error.message}`, 'error', 'permission-result');
            } finally {
                hideLoading();
            }
        }
        
        async function requestPermissions() {
            const hideLoading = showLoading(event.target);
            
            try {
                log('申请权限...', 'info', 'permission-result');
                
                // 申请相机权限
                try {
                    const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
                    log('相机和麦克风权限申请成功', 'success', 'permission-result');
                    stream.getTracks().forEach(track => track.stop());
                } catch (error) {
                    log(`相机/麦克风权限申请失败: ${error.message}`, 'error', 'permission-result');
                }
                
                // 申请位置权限
                try {
                    await new Promise((resolve, reject) => {
                        navigator.geolocation.getCurrentPosition(resolve, reject, { timeout: 5000 });
                    });
                    log('位置权限申请成功', 'success', 'permission-result');
                } catch (error) {
                    log(`位置权限申请失败: ${error.message}`, 'error', 'permission-result');
                }
                
                // 申请通知权限
                try {
                    if ('Notification' in window) {
                        const permission = await Notification.requestPermission();
                        log(`通知权限: ${permission}`, permission === 'granted' ? 'success' : 'warning', 'permission-result');
                    }
                } catch (error) {
                    log(`通知权限申请失败: ${error.message}`, 'error', 'permission-result');
                }
                
                // HarmonyOS 权限申请
                if (window.HarmonyBridge && window.HarmonyBridge.permissions) {
                    try {
                        const result = await window.HarmonyBridge.permissions.requestAll();
                        log(`HarmonyOS 权限申请结果: ${JSON.stringify(result)}`, 'info', 'permission-result');
                    } catch (error) {
                        log(`HarmonyOS 权限申请失败: ${error.message}`, 'error', 'permission-result');
                    }
                }
            } catch (error) {
                log(`权限申请失败: ${error.message}`, 'error', 'permission-result');
            } finally {
                hideLoading();
            }
        }
        
        async function openSettings() {
            const hideLoading = showLoading(event.target);
            
            try {
                log('尝试打开设置...', 'info', 'permission-result');
                
                if (window.HarmonyBridge && window.HarmonyBridge.system) {
                    await window.HarmonyBridge.system.openSettings();
                    log('设置页面打开成功', 'success', 'permission-result');
                } else {
                    log('无法打开设置页面，HarmonyOS 接口不可用', 'warning', 'permission-result');
                }
            } catch (error) {
                log(`打开设置失败: ${error.message}`, 'error', 'permission-result');
            } finally {
                hideLoading();
            }
        }
        
        // 返回功能
        function goBack() {
            if (window.history.length > 1) {
                window.history.back();
            } else {
                // 如果没有历史记录，尝试关闭页面或跳转到主页
                if (window.HarmonyBridge && window.HarmonyBridge.navigation) {
                    window.HarmonyBridge.navigation.goBack();
                } else {
                    window.location.href = 'index.html';
                }
            }
        }
        
        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('HarmonyOS 综合功能测试页面加载完成');
            
            // 检查 HarmonyBridge 可用性
            if (window.HarmonyBridge) {
                console.log('HarmonyBridge 可用，支持的功能:', Object.keys(window.HarmonyBridge));
            } else {
                console.log('HarmonyBridge 不可用，将使用 Web API 进行测试');
            }
            
            // 添加全局错误处理
            window.addEventListener('error', function(event) {
                console.error('全局错误:', event.error);
            });
            
            window.addEventListener('unhandledrejection', function(event) {
                console.error('未处理的 Promise 拒绝:', event.reason);
            });
        });
    </script>
</body>
</html>